home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / coherence / backend.py < prev    next >
Text File  |  2009-05-12  |  10KB  |  306 lines

  1. # -*- coding: utf-8 -*-
  2.  
  3. # Licensed under the MIT license
  4. # http://opensource.org/licenses/mit-license.php
  5.  
  6. # Copyright 2007,, Frank Scholz <coherence@beebits.net>
  7.  
  8. from coherence.extern.simple_plugin import Plugin
  9.  
  10. from coherence import log
  11.  
  12. import coherence.extern.louie as louie
  13.  
  14. from coherence.upnp.core.utils import getPage
  15. from coherence.extern.et import parse_xml
  16.  
  17.  
  18. class Backend(log.Loggable,Plugin):
  19.  
  20.     """ the base class for all backends
  21.  
  22.         if there are any UPnP service actions, that can't
  23.         be handled by the service classes itself, or need some
  24.         special adjustments for the backend, they need to be
  25.         defined here.
  26.  
  27.         Like maybe upnp_Browse for the CDS Browse action.
  28.     """
  29.  
  30.     implements = []  # list the device classes here
  31.                      # like [BinaryLight'] or ['MediaServer','MediaRenderer']
  32.  
  33.     logCategory = 'backend'
  34.  
  35.     def __init__(self,server,**kwargs):
  36.         """ the init method for a backend,
  37.             should probably most of the time be overwritten
  38.             when the init is done, send a signal to its device
  39.  
  40.             the device will then setup and announce itself,
  41.             after that it calls the backends upnp_init method
  42.         """
  43.         self.config = kwargs
  44.         self.server = server # the UPnP device that's hosting that backend
  45.  
  46.         """ do whatever is necessary with the stuff we can
  47.             extract from the config dict,
  48.             connect maybe to an external data-source and
  49.             start up the backend
  50.             after that's done, tell Coherence about it
  51.         """
  52.         self.init_completed()
  53.  
  54.     def init_completed(self, *args, **kwargs):
  55.         """ inform Coherence that this backend is ready for
  56.             announcement
  57.             this method just accepts any form of arguments
  58.             as we don't under which circumstances it is called
  59.         """
  60.         louie.send('Coherence.UPnP.Backend.init_completed',
  61.                 None, backend=self)
  62.  
  63.     def upnp_init(self):
  64.         """ this method gets called after the device is fired,
  65.             here all initializations of service related state variables
  66.             should happen, as the services aren't available before that point
  67.         """
  68.         pass
  69.  
  70.  
  71. class BackendStore(Backend):
  72.  
  73.     """ the base class for all MediaServer backend stores
  74.     """
  75.  
  76.     logCategory = 'backend_store'
  77.  
  78.     def __init__(self,server,*args,**kwargs):
  79.         """ the init method for a MediaServer backend,
  80.             should probably most of the time be overwritten
  81.             when the init is done, send a signal to its device
  82.  
  83.             the device will then setup and announce itself,
  84.             after that it calls the backends upnp_init method
  85.         """
  86.         self.config = kwargs
  87.         self.server = server # the UPnP device that's hosting that backend
  88.         self.update_id = 0
  89.  
  90.         """ do whatever is necessary with the stuff we can
  91.             extract from the config dict
  92.         """
  93.  
  94.         """ in case we want so serve something via
  95.             the MediaServer web backend
  96.  
  97.             the BackendItem should pass an URI assembled
  98.             of urlbase + '/' + id to the DIDLLite.Resource
  99.         """
  100.         self.urlbase = kwargs.get('urlbase','')
  101.         if not self.urlbase.endswith('/'):
  102.             self.urlbase += '/'
  103.  
  104.         self.wmc_mapping = {'4':'4', '5':'5', '6':'6','7':'7','14':'14','F':'F',
  105.                             '11':'11','16':'16','B':'B','C':'C','D':'D',
  106.                             '13':'13', '17':'17',
  107.                             '8':'8', '9':'9', '10':'10', '15':'15', 'A':'A', 'E':'E'}
  108.  
  109.         self.wmc_mapping.update({'4':lambda: self._get_all_items(0),
  110.                                  '8':lambda: self._get_all_items(0),
  111.                                  'B':lambda: self._get_all_items(0),
  112.                                 })
  113.  
  114.         """ and send out the signal when ready
  115.         """
  116.         #louie.send('Coherence.UPnP.Backend.init_completed', None, backend=self)
  117.  
  118.     def release(self):
  119.         """ if anything needs to be cleaned up upon
  120.             shutdown of this backend, this is the place
  121.             for it
  122.         """
  123.         pass
  124.  
  125.  
  126.     def _get_all_items(self,id):
  127.         """ a helper method to get all items as a response
  128.             to some XBox 360 UPnP Search action
  129.             probably never be used as the backend will overwrite
  130.             the wmc_mapping with more appropriate methods
  131.         """
  132.         items = []
  133.         item = self.get_by_id(id)
  134.         if item is not None:
  135.             containers = [item]
  136.             while len(containers)>0:
  137.                 container = containers.pop()
  138.                 if container.mimetype not in ['root', 'directory']:
  139.                     continue
  140.                 for child in container.get_children(0,0):
  141.                     if child.mimetype in ['root', 'directory']:
  142.                         containers.append(child)
  143.                     else:
  144.                         items.append(child)
  145.         return items
  146.  
  147.     def get_by_id(self,id):
  148.         """ called by the CDS or the MediaServer web
  149.  
  150.             id is the id property of our DIDLLite item
  151.  
  152.             if this MediaServer implements containers, that can
  153.             share their content, like 'all tracks', 'album' and
  154.             'album_of_artist' - they all have the same track item as content -
  155.             then the id may be passed by the CDS like this:
  156.  
  157.             'id@container' or 'id@container@container@container...'
  158.  
  159.             therefore a
  160.  
  161.             if isinstance(id, basestring):
  162.                 id = id.split('@',1)
  163.                 id = id[0]
  164.  
  165.             may be appropriate as the first thing to do
  166.             when entering this method
  167.  
  168.             should return
  169.  
  170.             - None when no matching item for that id is found,
  171.             - a BackendItem,
  172.             - or a Deferred
  173.  
  174.         """
  175.  
  176.         return None
  177.  
  178. class BackendItem(log.Loggable):
  179.  
  180.     """ the base class for all MediaServer backend items
  181.     """
  182.  
  183.     logCategory = 'backend_item'
  184.  
  185.     def __init__(self, *args, **kwargs):
  186.         """ most of the time we collect the necessary data for
  187.             an UPnP ContentDirectoryService Container or Object
  188.             and instantiate it here
  189.  
  190.             self.item = DIDLLite.Container(id,parent_id,name,...)
  191.               or
  192.             self.item = DIDLLite.MusicTrack(id,parent_id,name,...)
  193.  
  194.             To make that a valid UPnP CDS Object it needs one or
  195.             more DIDLLite.Resource(uri,protocolInfo)
  196.  
  197.             self.item.res = []
  198.             res = DIDLLite.Resource(url, 'http-get:*:%s:*' % mimetype)
  199.  
  200.                 url : the urlbase of our backend + '/' + our id
  201.  
  202.             res.size = size
  203.             self.item.res.append(res)
  204.         """
  205.         self.name = u'my_name' # the basename of a file, the album title,
  206.                                # the artists name,...
  207.                                # is expected to be unicode
  208.         self.item = None
  209.         self.update_id = 0 # the update id of that item,
  210.                            # when an UPnP ContentDirectoryService Container
  211.                            # this should be incremented on every modification
  212.  
  213.         self.location = None # the filepath of our media file, or alternatively
  214.                              # a FilePath or a ReverseProxyResource object
  215.  
  216.         self.cover = None # if we have some album art image, let's put
  217.                           # the filepath or link into here
  218.  
  219.     def get_children(self,start=0,end=0):
  220.         """ called by the CDS and the MediaServer web
  221.             should return
  222.  
  223.             - a list of its childs[start:end]
  224.             - or a Deferred
  225.  
  226.             if end == 0, the request is for all childs
  227.             after start - childs[start:]
  228.         """
  229.         pass
  230.  
  231.     def get_child_count(self):
  232.         """ called by the CDS
  233.             should return
  234.  
  235.             - the number of its childs - len(childs)
  236.             - or a Deferred
  237.  
  238.         """
  239.  
  240.     def get_item(self):
  241.         """ called by the CDS and the MediaServer web
  242.             should return
  243.  
  244.             - an UPnP ContentDirectoryServer DIDLLite object
  245.         """
  246.         return self.item
  247.  
  248.     def get_name(self):
  249.         """ called by the MediaServer web
  250.             should return
  251.  
  252.             - the name of the item,
  253.               it is always expected to be in unicode
  254.         """
  255.         return self.name
  256.  
  257.     def get_path(self):
  258.         """ called by the MediaServer web
  259.             should return
  260.  
  261.             - the filepath where to find the media file
  262.               that this item does refer to
  263.         """
  264.         return self.location
  265.  
  266.     def get_cover(self):
  267.         """ called by the MediaServer web
  268.             should return
  269.  
  270.             - the filepath where to find the album art file
  271.  
  272.             only needed when we have created for that item
  273.             an albumArtURI property that does point back to us
  274.         """
  275.         return self.cover
  276.  
  277.  
  278. class BackendRssMixin:
  279.  
  280.     def update_data(self,rss_url,container=None,encoding="utf-8"):
  281.         """ creates a deferred chain to retrieve the rdf file,
  282.             parse and extract the metadata and reschedule itself
  283.         """
  284.  
  285.         def fail(f):
  286.             self.info("fail %r", f)
  287.             self.debug(f.getTraceback())
  288.             return f
  289.  
  290.         dfr = getPage(rss_url)
  291.         dfr.addCallback(parse_xml, encoding=encoding)
  292.         dfr.addErrback(fail)
  293.         dfr.addCallback(self.parse_data,container)
  294.         dfr.addErrback(fail)
  295.         dfr.addBoth(self.queue_update,rss_url,container)
  296.         return dfr
  297.  
  298.     def parse_data(self,xml_data,container):
  299.         """ extract media info and create BackendItems
  300.         """
  301.         pass
  302.  
  303.     def queue_update(self, error_or_failure,rss_url,container):
  304.         from twisted.internet import reactor
  305.         reactor.callLater(self.refresh, self.update_data,rss_url,container)
  306.